#include "xRenderTarget.h"
#include "xViewPort.h"
#include "xCamera.h"
#include "xLogManager.h"
#include "XRenderSystem.h"
#include "XEngine.h"
#include "xSurface.h"


namespace XE	
{

	xRenderTarget::xRenderTarget(const xString& name,const  RenderConfig& config)
		:m_Name(name),m_pBlackSurface(NULL),m_pDepthSurface(NULL),m_Config(config)
	{

	}

	xRenderTarget::~xRenderTarget()
	{
		SafeDelete(m_pDepthSurface)
		SafeDelete(m_pBlackSurface)

		DestoryAllViewPort();
	}


	xViewPort*  xRenderTarget::CreateViewPort( const xString& name, xCamera* pCamera,\
		float left ,float top ,float width ,float height,float minz,float maxz )
	{
		assert(pCamera);
		xViewPort* pViewPort = GetViewPortByName(name);
		if(pViewPort!=NULL)
		{
			xLogMessager::getSingleton().logMessage("Create viewPort Fail ,has same name View Port");
			return NULL;
		}

		pViewPort = new xViewPort(pCamera,this,left,top,width,height,minz,maxz);
		m_ViewPortMap.insert(std::make_pair(name,pViewPort));

		return pViewPort;
	}

	
	xViewPort* xRenderTarget::GetViewPortByName(const xString& name)
	{
		xViewPortMap::iterator it = m_ViewPortMap.find(name);
		if(it==m_ViewPortMap.end())
			return NULL;
		return it->second;
	}


	bool xRenderTarget::DestoryViewPort(const  xString& name)
	{
		xViewPortMap::iterator it = m_ViewPortMap.find(name);
		 if(it!=m_ViewPortMap.end())
		 {
			 delete it->second;
			 m_ViewPortMap.erase(it);
			 return true;
		 }
		return false;
	}

	 void xRenderTarget::DestoryAllViewPort()
	 {
		 xViewPortMap::iterator it = m_ViewPortMap.begin();
		 for(;it!=m_ViewPortMap.end();++it)
		 {
			 delete it->second;
		 }

		 m_ViewPortMap.clear();
	 }




	 HRESULT xRenderTarget::update(XRenderSystem* pRender)
	 {
	  
		 if(m_Config.m_hDeviceWindow==NULL ||IsIconic(m_Config.m_hDeviceWindow))
			 return X_OK;


		 if(pRender->IsDeviceLost())
		 	 pRender->ResetDevice();


		 HRESULT hr = X_OK;
		 if(FAILED(pRender->SetRenderColorSurface(0,m_pBlackSurface)))
		 {
			 xLogMessager::getSingleton().logMessage("SetRenderSurface Fail");
			 throw("SetRenderSurface Fail");
		 }

		 if(FAILED(pRender->SetDepthStencilSurface(m_pDepthSurface)))
		 {
			 xLogMessager::getSingleton().logMessage("SetDepthStencilSurface Fail");
			 throw("SetDepthStencilSurface Fail");
		 }

		
		 xViewPortMap::iterator it = m_ViewPortMap.begin();
		 xViewPortMap::iterator itend = m_ViewPortMap.end();
		 for(;it!=itend;++it)
		 {
			 if(it->second==NULL)
				 continue;
			 if( FAILED(pRender->SetViewPort(it->second)))
			 {
				 xLogMessager::getSingleton().logMessage("SetViewPort Fial");
				 continue;
			 }

			 xCamera* pCam = it->second->GetCamera();
			 if(pCam!=NULL)
				 pCam->CaptureOneFrame();

		 }

		 if(pRender->isRenderFps())
			 pRender->Renderfps();

        return    Present();
		 //return pRender->Present();

	 }


		 

}